import axios from "axios";
import { showToast } from "vant";

const timeout = 1000 * 10; //设置超时时间
const request = axios.create({
    baseURL: "http://121.89.205.189:3000/",
    // baseURL: "http://localhost:3001/",
    timeout,
})

interface IerrorMessages {
    [prop: string]: string;
}

const errorMessages: IerrorMessages = {
    'Request failed with status code 404': "接口异常,请再看看",
    [`timeout of ${timeout}ms exceeded`]: "接口超时",

}

//请求拦截
request.interceptors.request.use(
    (config) => {
        // 获取 token
        const { token } = JSON.parse(localStorage.getItem('user') || "{}")
        //判断token存在就写入到config的headers中
        if(token){
            (config.headers as any).token = token;
        }

        return config;
    },
    (error) => {
        return Promise.reject(error);
    }
);

// 响应拦截
request.interceptors.response.use(
    (response) => {
        const { data } = response;

        //判断业务状态码是否为200
        if (data.code === "200") {
            return data;
        } else {
            showToast({ message: data.message, position: "top" });
            throw new Error(data.message);
        }
    },
    (error) => {
        //2xx之外的状态码进入
        showToast({
            message: errorMessages[error.message] || "网络异常,请稍后重试",
            position: "top"
        });
        // console.log(error.message)
        return Promise.reject(error);
    }
);


export default request;